package com.insightg3.android;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;
import android.util.Xml;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

 

public class AndroidUtils {

    private static String keyfile = "keyword_map.xml";

    public static Bitmap returnBitMap(String url, int newWidth, int newHeight) {
    	Log.d("URL", url);
		   URL myFileUrl = null; 
		   Bitmap bitmap = null; 
		   try { 
		            myFileUrl = new URL(url); 
		   } catch (MalformedURLException e) { 
		            e.printStackTrace(); 
		   } 
		   try { 
		            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); 
		            conn.setDoInput(true); 
		            conn.connect(); 
		            InputStream is = conn.getInputStream(); 
		            bitmap = BitmapFactory.decodeStream(is); 
		            is.close(); 
		   } catch (IOException e) { 
		
		            e.printStackTrace(); 
		
		   } 
		   if(newWidth == 0 || newHeight == 0){
		       return bitmap; 
		   }
		   return resizeImage(bitmap, newWidth, newHeight);
	 } 

     public static Bitmap resizeImage(Bitmap bitmapOrg, int newWidth, int newHeight){

         int width = bitmapOrg.getWidth();
         int height = bitmapOrg.getHeight();

         // calculate the scale
         float scaleWidth = ((float) newWidth) / width;                 
         float scaleHeight = ((float) newHeight) / height;

         // create matrix for the manipulation
         Matrix matrix = new Matrix();

  

         // resize the bit map
         matrix.postScale(scaleWidth, scaleHeight);

  

//             // rotate the Bitmap
//             matrix.postRotate(45);

             // recreate the new Bitmap

         Bitmap bitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,

                           width, height, matrix, true);

         return bitmap;

     }
         
     public static String translateString(String strOrg, Language lOrg, Language lTag){
         String rtnString = strOrg;
         try {
        	 Translate.setHttpReferrer("http//www.spectrum.co.jp");
             rtnString = Translate.execute(strOrg, lOrg, lTag);
         } catch (Exception e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } 
         return rtnString;
      }
         
     public static String output2XML(){

         String strRtnXML = "";
         XmlSerializer serializer = Xml.newSerializer();
         StringWriter writer = new StringWriter();

         try{
             serializer.setOutput(writer);

             // <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
             serializer.startDocument("UTF-8",true);

             // <translation_key number=”1″>
             serializer.startTag("","translation_key");
             //serializer.attribute("","number",String.valueOf(1));

             //<key data="2009-09-23″>
             serializer.startTag("","key");
             //serializer.attribute("","date","2009-09-23″);

             // <japan>ソニー</japan>
             serializer.startTag("","japan");
             serializer.text("ソニー");
             serializer.endTag("","japan");

             // <china>ソニー</china>
             serializer.startTag("","china");
             serializer.text("索尼");
             serializer.endTag("","china");

             //</key>
             serializer.endTag("","key");
             // </translation_key>
             serializer.endTag("","translation_key");
             serializer.endDocument();
             strRtnXML = writer.toString();
         }
         catch(Exception e)
         {
             throw new RuntimeException(e);
         }
         return strRtnXML;
      }

     public static Language getTranslateLanguage(String lang){

         if("Japan".equals(lang)){

             return Language.JAPANESE;

         }

         else if("China".equals(lang)){

             return Language.CHINESE_SIMPLIFIED;

         }

         return Language.ENGLISH;

      }

     public static String getAutoTranslation(Activity activity, String key, String tagLang){

         Log.d("getAutoTranslation start:", key);

         String rtnKey = key;

         rtnKey = AndroidUtils.getGoogleTranslation(key, tagLang);

         Log.d("getAutoTranslation rtnKey 1:", rtnKey);
         List<Map> keyMapList = readFile(activity, keyfile);

         String orgLang = tagLang;

         if("Japan".equals(tagLang)){
           orgLang = "China";
         }
         else if("China".equals(tagLang)){
           orgLang = "Japan";
         }

         for(Map keyMap : keyMapList){
              if(key.equals(keyMap.get(orgLang).toString())){
                 rtnKey = keyMap.get(tagLang).toString();
                 Log.d("getAutoTranslation found key:", rtnKey);
                 break;
              }
         }
         Log.d("getAutoTranslation rtnKey=:", rtnKey);
         return rtnKey;
     }

     public static String getGoogleTranslation(String key, String tagLang){

         String engKey = key;
         String rtnKey = key;

         Log.d("getGoogleTranslation start　tagLang=", tagLang);

         if("Japan".equals(tagLang)){
           engKey = AndroidUtils.translateString(key, Language.ENGLISH, Language.JAPANESE);
           Log.d("getGoogleTranslation engKey=", engKey);
           rtnKey = AndroidUtils.translateString(engKey, Language.CHINESE_SIMPLIFIED, Language.JAPANESE);
           Log.d("getGoogleTranslation rtnKey=", rtnKey);
         }
         else if("China".equals(tagLang)){
           engKey = AndroidUtils.translateString(key, Language.ENGLISH, Language.CHINESE_SIMPLIFIED);
           Log.d("getGoogleTranslation engKey=", engKey);
           rtnKey = AndroidUtils.translateString(engKey, Language.JAPANESE, Language.CHINESE_SIMPLIFIED);
           Log.d("getGoogleTranslation rtnKey=", rtnKey);
         }
         return rtnKey;
     }

     public static List<Map> readFile(Activity activity, String filepath){

		 List<Map> rtnList  = new ArrayList<Map>();
		 XmlPullParser parser = Xml.newPullParser();
         try {
	           FileInputStream inputStream=activity.openFileInput(filepath);
	           parser.setInput(inputStream, "UTF-8");
	           boolean blnItemStart = false;
	           Map keyMap = new HashMap();
                   // XML文章の終わりまでループして解析すや1�7
              for (int eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser
                      .next()) {
                   String tagName;
                   String tagText;
                   switch (eventType) {
                   // TAGの始まり
                   case XmlPullParser.START_TAG:
                      // TAGの名前を取得する
                      tagName = parser.getName();
                      if (tagName.equals("key")) {
                          blnItemStart = true;
                      }
                      else
                      // TAGの名前がjapan
                      if (tagName.equals("Japan")) {
                          // 次の要素へ
                          parser.next();
                          // 要素がTEXTだったら内容を取り出い
                          if (parser.getEventType() == XmlPullParser.TEXT) {
                             tagText = parser.getText();
                             keyMap.put("Japan", tagText);
                          }
                      }
                      else if (tagName.equals("China")) {
                          // 次の要素へ
                          parser.next();
                          // 要素がTEXTだったら内容を取り出い1�7
                          if (parser.getEventType() == XmlPullParser.TEXT) {
                             tagText = parser.getText();
                             keyMap.put("China", tagText);
                          }
                      }
                      break;
                   // TAGのおわり
                   case XmlPullParser.END_TAG:
                      // TAGの名前を取得する
                      tagName = parser.getName();
                      if (tagName.equals("key") && blnItemStart) {
                          rtnList.add(keyMap);
                          keyMap = new HashMap();
                          blnItemStart = false;
                      }
                      break;
                   }

               }
               Log.d("paser registed KeyList xml", rtnList.toString());
            } catch (XmlPullParserException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
            } catch (FileNotFoundException e) {
			   // TODO Auto-generated catch block
			   Log.d("file not found", "file is not found");
			}catch (IOException e) {
			       e.printStackTrace();
			}
			return rtnList;
     }
}
